package versionx

import (
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/datax/mapx"
)

// 输出变化的字段
func (s *Object) ToMapVersion() (r datax.M) {
	r = datax.M{}
	if s.enableVersion {
		s.toMapVersion(r)
		s.RefVersionComplete()
	} else {
		s.toMap(r)
	}

	return
}
func (s *Object) toMapVersion(target datax.M) {
	versions := s.RefVersions()
	lastVersion := s.lastVersion
	for field, val := range s.data {
		key := s.RefFieldPath() + "/" + field
		if versions[key] <= lastVersion {
			continue
		}
		switch v := val.(type) {
		case datax.M:
			if v != nil {
				tm := datax.M{}
				target[field] = tm
				s.RefClass(field).toMapVersion(tm)
			}
		default:
			target[field] = v
		}
	}
}

// 输出所有字段
func (s *Object) ToMap() (r datax.M) {
	r = datax.M{}
	s.toMap(r)
	return
}

func (s *Object) toMap(target datax.M) {
	for field, val := range s.data {
		switch v := val.(type) {
		case datax.M:
			if v != nil {
				tm := datax.M{}
				target[field] = tm
				s.RefClass(field).toMap(tm)
			}
		default:
			target[field] = v
		}
	}
}

// 输出指定字段
func (s *Object) ToMapByField(fieldMap datax.M) (r datax.M) {
	r = datax.M{}
	toMapByField(s.data, fieldMap, r)
	return r
}

func toMapByField(data, fieldMap datax.M, r datax.M) {
	for field, fieldValue := range fieldMap {
		dataVal := data[field]
		switch v := dataVal.(type) {
		case datax.M:
			if v != nil {
				tm := datax.M{}
				r[field] = tm
				if fieldValue == nil {
					mapx.Copy(v, tm)
				} else {
					toMapByField(v, fieldValue.(datax.M), tm)
				}
			} else {
				r[field] = nil
			}
		default:
			r[field] = v
		}
	}
	return
}
func toMapByData(data, fieldMap datax.M, r datax.M) {
	for field, fieldValue := range fieldMap {
		dataVal := data[field]
		switch v := dataVal.(type) {
		case datax.M:
			if v != nil {
				tm := datax.M{}
				r[field] = tm
				if fieldValue == nil {
				} else {
					toMapByField(v, fieldValue.(datax.M), tm)
				}
			} else {
				r[field] = nil
			}
		default:
			r[field] = v
		}
	}
	return
}
